package com.cyt.base.exception;

import com.cyt.base.exception.base.BaseException;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定义异常处理器
 * 通过异常直接返回，不需要经过controller是不是有性能问题
 *  if (countUserPostById(postId) > 0){
 *     throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName()));
 *  }
 * @author taocongcong
 */
@ControllerAdvice
@Order(1)
public class DefaultExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);
    
    /**
     * 请求方式不支持
     */
    @ResponseBody
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public ReturnResult handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return new ReturnResult(ErrorCode.CODE_1, "不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ReturnResult notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return new ReturnResult(ErrorCode.CODE_1, "运行时异常:" + e.getMessage());
    }

    /**
     * 自定义异常
     */
    @ResponseBody
    @ExceptionHandler(BaseException.class)
    public ReturnResult handleUCException(BaseException e){
        log.error("基础自定义异常:", e);
        return new ReturnResult(ErrorCode.CODE_1, "基础自定义异常:" + e.getMsg());
    }
}
